﻿using System.Configuration;
using System.IO;


namespace DataLayer.Generic
{
    public sealed class GenericDataSection : ConfigurationSection
    {
        public const string none = "none";
        public const string file = "file";
        public const string debug = "debug";

        [ConfigurationProperty("LogType", DefaultValue = none)]
        private string LogType
        {
            get
            {               
                return this["LogType"].ToString().ToLower();
            }
            set
            {
                this["LogType"] = value;
            }
        }
        [ConfigurationProperty("LogFile", DefaultValue="log.txt")]
        private string LogFile
        {
            get
            {
                return (string) this["LogFile"];
            }
            set
            {
                this["LogFile"] = value;
            }
        }
        [ConfigurationProperty("DeleteExistingFile", DefaultValue=true)]
        private bool DeleteExistingFile
        {
            get
            {
                return (bool)this["DeleteExistingFile"];
            }
            set
            {
                this["DeleteExistingFile"] = value;
            }
        }
        public TextWriter Logger
        {
            get
            {
                if(LogType == none)
                    return null;

                if(LogType == file && string.IsNullOrEmpty(LogFile))
                    throw new ConfigurationErrorsException("To use File logging you must also specify a LogFile attribute. Alternatively 'debug' will log to the debug output");

                if (LogType == file)
                    return new FileLogger(LogFile, DeleteExistingFile);
               
                return new DebuggerWriter();
            }
        }
    }
}
